package com.example.jwt.controller;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.jwt.appuser.AppUser;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static org.springframework.http.HttpStatus.FORBIDDEN;
import static org.springframework.http.HttpStatus.OK;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;

@Slf4j
@RestController
@RequestMapping()
public class PagesController {

    @GetMapping("/hello")
    public String showUsername(){
        return "here in jwt";
    }

    @PostMapping("/get")
    public ResponseEntity<String> getToken(AppUser appuser) {
        Algorithm algorithm = Algorithm.HMAC256("secret".getBytes());
        String accessToken = JWT.create()
                .withSubject(appuser.getUsername())
                .withExpiresAt(new Date(System.currentTimeMillis() + 10 * 60 * 1000))
                .withClaim("name", appuser.getUsername())
                .sign(algorithm);
        log.info("new token :", accessToken);
        return new ResponseEntity(accessToken, HttpStatus.OK);
    }

    @PostMapping("/verify")
    public ResponseEntity<String> verifyToken(@RequestParam("token") String token) {
        try {
//            String token = jsonParam.getString("token");
            log.info("verify token :", token);
            Algorithm algorithm = Algorithm.HMAC256("secret".getBytes());
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT decodedJWT = verifier.verify(token);
            String username = decodedJWT.getSubject();
            String name = decodedJWT.getClaim("name").asString();
            log.info("username :", username);
            log.info("name :", name);
            UsernamePasswordAuthenticationToken authenticationToken =
                    new UsernamePasswordAuthenticationToken(username, null, null);
            return new ResponseEntity(authenticationToken, OK);
        } catch (Exception e) {
            log.error("Error logging in: {}", e.getMessage());
            return new ResponseEntity(e.getMessage(), FORBIDDEN);
        }
    }

}
